package com.example.statistics.ui.purchase

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.example.statistics.R
import com.example.statistics.bean.*
import com.example.statistics.common.BaseActivity
import com.example.statistics.common.MultiSelectListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DownloadDialogHttpCallback
import com.example.statistics.net.callback.UploadDialogHttpCallback
import com.example.statistics.ui.bank.Config.toStatementActivity
import com.example.statistics.utils.*
import com.jhj.httplibrary.HttpCall
import com.jhj.prompt.fragment.AlertFragment
import com.jhj.slimadapter.SlimAdapter
import kotlinx.android.synthetic.main.activity_base_pruchase_product.*
import kotlinx.android.synthetic.main.dialog_input.view.*
import kotlinx.android.synthetic.main.layout_purchase_type_title.view.*
import kotlinx.android.synthetic.main.table_row_storage_fee.view.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.onLongClick
import org.jetbrains.anko.toast
import java.io.File
import java.math.BigDecimal
import java.net.URLDecoder
import kotlin.math.abs


abstract class BasePurchaseProductActivity : BaseActivity() {


    companion object {
        const val TYPE_CERTIFICATE = "certificate"
        const val TYPE_BILL = "bill"
    }


    var purchaseId = -1
    var containerNo = ""
    var productValuationWeight = 0.0 //计价重量
    var purchaseProductBean: PurchaseProductBean? = null
    private var certificateAdapter: SlimAdapter? = null
    private var billAdapter: SlimAdapter? = null
    private var clearanceAdapter: SlimAdapter? = null
    var feeDetailAdapter: SlimAdapter? = null

    open val childrenViewRes: Int? = null
    open val billTotalAmount = 0.0

    //仓储费
    var storageFee = 0.0

    //结算费
    var settlementTotalAmount = 0.0

    //清关费
    var clearanceFee = 0.0

    // 税款
    var taxFee = 0.0

    //融资款
    var financingFee = 0.0

    //货款
    var futuresFee = 0.0


    override val title: String
        get() = intent.getStringExtra(Constants.TITLE).orEmpty()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_base_pruchase_product)
        childrenViewRes?.let {
            val childView = layoutInflater.inflate(it, null, false)
            layout_frame.addView(childView)
        }

        purchaseId = intent.getIntExtra(Constants.PURCHASE_PRODUCT_ID, -1)
        certificateAdapter = fileAdapter(TYPE_CERTIFICATE)
        billAdapter = fileAdapter(TYPE_BILL)
        initView()
        getPurchaseProductInfo()
        certificateAdapter?.attachTo(recycler_view_file)
        billAdapter?.attachTo(recycler_view_fee_file)
        //refreshFee()
    }


    private fun getPurchaseProductInfo(): Unit =
        httpGet<PurchaseProductBean>(UrlConfig.PURCHASE_PRODUCT_DATA, config = {
            listParams = listOf("id" to purchaseId)
            isShowDialog = true
        }) { data ->
            if (data != null) {
                purchaseProductBean = data
                containerNo = purchaseProductBean?.containerNo.orEmpty()
                productValuationWeight = if (data.weightUnit == "磅") {
                    if (data.productNumber < 1300) {
                        data.productNumber * 20.toDouble()
                    } else {
                        data.productNumber * 13.607679
                    }
                } else {
                    data.productWeight
                }

                certificateAdapter?.setDataList(data.fileList?.filter { it.type == TYPE_CERTIFICATE }
                    .orEmpty())
                billAdapter?.setDataList(data.fileList?.filter { it.type == TYPE_BILL }.orEmpty())

                clearanceFee(data.clearanceFeeList)
                httpSettlement()
                shipment(data.purchaseSalesList)
                if (data.storageFeeList != null) {
                    storageFee(data.storageFeeList)
                }
                initData(data)

                //基本信息
                tv_container_no.contentText = "集装箱号：${data.containerNo}"
                tv_contract_no.contentText = "合同号：${data.contractNo}"
                tv_product_price.contentText = "单    价：${data.priceUnit}${data.productPrice}"
                tv_product_weight.contentText = "商品重量：${data.productWeight}${data.weightUnit}"
                tv_product_number.contentText = "件    数：${data.productNumber}件"
                tv_total_price.contentText = "商品总价：${data.priceUnit}${data.productTotalPrice}"
                tv_remark.contentText = data.remark
                tv_remark.visibility = if (!data.remark.isNullOrBlank()) View.VISIBLE else View.GONE

                //
                portInfo(data.shippingInfo)
                tv_flow_city.contentText = data.purchaseSalesList?.joinToString { it.customerName }.orEmpty()
                updateBillTotalAmount()
            }
        }


    open fun initData(bean: PurchaseProductBean) {}

    open fun refreshFee() {
        layout_fee.visibility = View.VISIBLE
        val list = mutableListOf<String>()
        val differenceFee = billTotalAmount.subEx(settlementTotalAmount).toDouble() //付款总金额与商品总价之间差价
        val differenceStatus = if (differenceFee > 0) "欠" else if (differenceFee == 0.0) "" else "多"
        val profit = purchaseProductBean?.salesTotalAmount.subEx(billTotalAmount)
            .subEx(purchaseProductBean?.purchaseSalesList?.sumEx { it.freight + it.unloadingFee }).toDouble() //利润
        val profitStatus = if (profit > 0.0) "赢" else if (profit < 0.0) "亏" else "" //
        list.add("货        款：${futuresFee.display()}")
        if (this is PurchaseFuturesProductActivity) {
            list.add("融        资：${financingFee.display()}")
            list.add("税        款：${taxFee.display()}")
        }
        list.add("清        关：${clearanceFee.display()}")
        list.add("仓        储：${storageFee.display()}")
        list.add("成本单价：${billTotalAmount.mulEx(10).divEx(productValuationWeight).display()}")
        list.add("总  成  本：${billTotalAmount.display()}")
        list.add("")
        list.add("结算金额：${settlementTotalAmount.display()}")
        list.add("销售单价：${purchaseProductBean?.salesTotalAmount.mulEx(10).divEx(productValuationWeight).display()}")
        list.add("结算差价：${differenceStatus}${abs(differenceFee)}")
        list.add("利        润：${profitStatus}${abs(profit)}")
        recycler_view_fee.visibility = View.VISIBLE
        feeDetailAdapter?.setDataList(list)
    }

    /**
     *  如果刷新后的总商品费用与保存的不一致，进行修改
     */
    fun updateBillTotalAmount(): Unit = modify("billTotalAmount" to billTotalAmount) {
        purchaseProductBean?.billTotalAmount = it?.billTotalAmount ?: 0.0
    }

    open fun initView() {
        layout_files.tv_title.text = "手续"
        layout_fee_files.tv_title.text = "结算单"
        layout_settlement.tv_title.text = "付款单"
        layout_storage.tv_title.text = "仓储费"
        layout_clearance.tv_title.text = "清关费"
        layout_shipment.tv_title.text = "出货信息"

        recycler_view_clearance.layoutManager = GridLayoutManager(this, 2)
        clearanceAdapter = slimAdapter<ClearanceBean>(R.layout.list_item_clearance_fee_display) {
            text(R.id.tv_key, "${it.name}：").text(R.id.tv_value, it.value.toString())
        }.attachTo(recycler_view_clearance)

        //费用信息
        recycler_view_fee.layoutManager = GridLayoutManager(this, 2)
        feeDetailAdapter = slimAdapter<String>(R.layout.list_item_purchase_fee_detail) {
            if (it.replace(" ", "").contains("利润")) {
                val color = if (it.contains("赢")) Color.RED else Color.GREEN
                val span = SpannableString(it)
                span.setSpan(ForegroundColorSpan(color), 0, it.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                text(R.id.text_view, span)
            } else {
                text(R.id.text_view, it)
            }
        }.attachTo(recycler_view_fee)

        layout_info_display.onClick {
            activityForResult<PurchaseProductEditActivity>(Constants.DATA to purchaseProductBean) {
                getPurchaseProductInfo()
            }
        }

        layout_post.onClick {
            activityForResult<PortInfoEditActivity>(
                Constants.AGENT_ID to purchaseProductBean?.agentId,
                Constants.CONTAINER_NO to purchaseProductBean?.containerNo,
                Constants.PURCHASE_PRODUCT_ID to purchaseProductBean?.ID
            ) {
                httpPortInfo()
            }
        }

        layout_storage.iv_add.onClick {
            activityForResult<StorageFeeEditActivity>(
                Constants.STORAGE to tv_cold_storage.contentText,
                Constants.START_DATE to purchaseProductBean?.shippingInfo?.warehousingDate,
                Constants.END_DATE to purchaseProductBean?.shippingInfo?.deliveryDate,
                Constants.CONTAINER_NO to containerNo,
                Constants.PURCHASE_PRODUCT_ID to purchaseId,
                Constants.WEIGHT to productValuationWeight,
                Constants.CITY to purchaseProductBean?.shippingInfo?.port
            ) {
                httpStorageFee()
            }
        }

        layout_clearance.iv_add.onClick {
            //有清关费用进入清关费用详情，无清关费用进入清关item列表
            if (!purchaseProductBean?.clearanceFeeList.isNullOrEmpty()) {
                getClearanceFeeData()
            } else {
                activityForResult<MultiSelectListActivity>(
                    Constants.TITLE to title,
                    Constants.TYPE to ClearanceBean::class.java,
                    Constants.PATH to UrlConfig.PURCHASE_CLEARANCE_FIELD_LIST,
                    Constants.DATA to purchaseProductBean?.clearanceFeeList?.map { it.id }
                ) { intent ->
                    purchaseProductBean?.clearanceFeeList =
                        (intent?.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>).orEmpty()
                    getClearanceFeeData()
                }
            }
        }

        /*layout_settlement.iv_add.onClick {
            activityForResult<SettlementFeeEditActivity>(
                Constants.CONTAINER_NO to purchaseProductBean?.containerNo,
                Constants.PURCHASE_PRODUCT_ID to purchaseId
            ) {
                httpSettlement()
            }
        }*/
        layout_settlement.iv_add.onClick {
            toStatementActivity(DefaultConfig.FUNC_PORT_PURCHASE, purchaseId, purchaseProductBean?.billTotalAmount.orEmpty()) {
                httpSettlement()
            }
        }
        layout_shipment.iv_add.onClick {
            actionDialog(
                "拉回入库" to {
                    activityForResult<PurchaseShipmentActivity>(
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.TYPE to "入库"
                    ) {
                        httpShipment()
                    }
                },
                "港口整出" to {
                    activityForResult<PurchaseShipmentActivity>(
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.TYPE to "销售"
                    ) {
                        httpShipment()
                    }
                })
        }

        layout_files.iv_add.onClick {
            fillSelector(TYPE_CERTIFICATE)
        }
        layout_fee_files.iv_add.onClick {
            fillSelector(TYPE_BILL)
        }
    }

    /**
     * 港口基本信息
     */
    private fun httpPortInfo() {
        httpGet<ShippingInfo>(UrlConfig.PURCHASE_PORT_DATA, config = {
            listParams = listOf("purchaseProductId" to purchaseProductBean?.ID)
        }) {
            portInfo(it)
        }
    }

    private fun portInfo(portInfo: ShippingInfo?) {
        tv_start_time.contentText = portInfo?.startDate.goTimeFormat()
        tv_ship_company.contentText = portInfo?.shipCompany.orEmpty()
        tv_arrival_time.contentText = portInfo?.arrivalDate.goTimeFormat()
        tv_port_position.contentText = portInfo?.port
        tv_warehousing_time.contentText = portInfo?.warehousingDate.goTimeFormat()
        tv_cold_storage.contentText = portInfo?.coldStorage.orEmpty()
        tv_delivery_time.contentText = portInfo?.deliveryDate.goTimeFormat()
    }


    /**
     * 仓储费
     */
    private fun httpStorageFee() {
        httpGet<List<StorageBean>>(UrlConfig.PURCHASE_STORAGE_FEE_LIST, config = {
            listParams = listOf("containerNo" to containerNo)
        }) {
            purchaseProductBean?.storageFeeList = it
            storageFee(it)
            updateBillTotalAmount()
        }
    }

    private fun storageFee(storageFeeList: List<StorageBean>?) {
        table_layout_storage.removeAllViews()
        if (storageFeeList.isNullOrEmpty()) {
            table_layout_storage.visibility = View.GONE
            return
        }
        table_layout_storage.visibility = View.VISIBLE
        val fieldView = inflater.inflate(R.layout.table_row_storage_fee_field, table_layout_storage, false)
        table_layout_storage.addView(fieldView)
        var amount = BigDecimal(0)
        storageFeeList.forEach { bean ->
            amount = amount.addEx(bean.storageFee)
            val view = inflater.inflate(R.layout.table_row_storage_fee, table_layout_storage, false)
            view.tv_storage.contentText = bean.storage
            view.tv_unit_price.contentText = bean.unitPrice.toString()
            view.tv_weight.contentText = bean.weight.toString()
            view.tv_storage.contentText = bean.storage
            view.tv_start_date.contentText =
                bean.startDate.goTimeFormat() + "\n" + bean.endDate.goTimeFormat()
            view.tv_storage_days.contentText = bean.storageDays.toString()
            view.tv_storage_fee.contentText = bean.storageFee.toString()
            view.onSingleLongClicked("编辑", "删除") { s ->
                if ("编辑" == s) {
                    activityForResult<StorageFeeEditActivity>(
                        Constants.ID to bean.ID,
                        Constants.STORAGE to bean.storage,
                        Constants.START_DATE to bean.startDate,
                        Constants.END_DATE to bean.endDate,
                        Constants.CONTAINER_NO to bean.containerNo,
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.WEIGHT to bean.weight,
                        Constants.CITY to purchaseProductBean?.shippingInfo?.port
                    ) {
                        httpStorageFee()
                    }
                } else {
                    messageDialog(msg = "是否删除${bean.storage}?") { _, _ ->
                        httpGet<StorageBean>(UrlConfig.PURCHASE_STORAGE_FEE_DELETE, config = {
                            listParams = listOf("id" to bean.ID)
                        }) {
                            httpStorageFee()
                        }
                    }
                }
            }
            table_layout_storage.addView(view)
        }
        storageFee = amount.toDouble()
        layout_storage.tv_fee.contentText = "(${amount})"
        refreshFee()
    }

    /**
     * 销售
     */
    private fun httpShipment() {
        httpGet<List<ShipmentBean>>(UrlConfig.PURCHASE_SALES_LIST, config = {
            listParams = listOf("purchaseProductId" to purchaseId)
        }) { shipmentList ->
            purchaseProductBean?.purchaseSalesList = shipmentList.orEmpty()
            shipment(shipmentList)
        }
    }

    private fun shipment(shipmentList: List<ShipmentBean>?) {
        table_layout_shipment.removeAllViews()
        val salesNumber = shipmentList?.sumEx { it.salesNumber }?.toInt()
        if (purchaseProductBean?.productNumber == salesNumber) {
            layout_shipment.iv_add.visibility = View.GONE
        } else {
            layout_shipment.iv_add.visibility = View.VISIBLE
        }
        if (shipmentList.isNullOrEmpty()) {
            table_layout_shipment.visibility = View.GONE
            return
        }
        table_layout_shipment.visibility = View.VISIBLE
        val filedView = inflater.inflate(R.layout.table_row_shipment_field, table_layout_shipment, false)
        table_layout_shipment.addView(filedView)
        shipmentList.forEach { shipmentBean ->
            val view = inflater.inflate(R.layout.table_row_shipment, table_layout_shipment, false)
            view.find<TextView>(R.id.tv_sales_date).contentText = shipmentBean.date.goTimeFormat()
            view.find<TextView>(R.id.tv_sales_customer).contentText = shipmentBean.customerName
            view.find<TextView>(R.id.tv_sales_price).contentText = shipmentBean.salesPrice.display()
            view.find<TextView>(R.id.tv_sales_number).contentText = shipmentBean.salesNumber.display()
            view.find<TextView>(R.id.tv_total_price).contentText = shipmentBean.totalPrice.display()
            view.find<TextView>(R.id.tv_freight).contentText = shipmentBean.freight.display()
            view.find<TextView>(R.id.tv_unloading_fee).contentText = shipmentBean.unloadingFee.display()
            view.onActionLongClicked(
                "对账单" to {
                    toStatementActivity(DefaultConfig.FUNC_PORT_SALES, shipmentBean.ID, shipmentBean.totalPrice.orEmpty()) {
                        httpSettlement()
                    }
                },
                "编辑" to {
                    activityForResult<PurchaseShipmentActivity>(
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.TYPE to shipmentBean.type,
                        Constants.DATA to shipmentBean
                    ) {
                        httpShipment()
                    }
                },
                "删除" to {
                    messageDialog(msg = "是否删除${shipmentBean.customerName}?") { _, _ ->
                        httpGet<Any>(UrlConfig.PURCHASE_SALES_DELETE, config = {
                            listParams = listOf("id" to shipmentBean.ID)
                        }) {
                            httpShipment()
                        }
                    }
                }
            )
            table_layout_shipment.addView(view)
        }

        //根据结算的金额计算销售总额
        val salesTotalPrice = shipmentList.sumEx { it.totalPrice }.toDouble()
        if (purchaseProductBean?.salesTotalAmount != salesTotalPrice) {
            modify("salesTotalAmount" to salesTotalPrice) {
                purchaseProductBean?.salesTotalAmount = it?.salesTotalAmount ?: 0.0
            }
        }
    }


    /**
     * 付款单
     */
    private fun httpSettlement() {
        httpGet<List<SettlementFeeBean>>(UrlConfig.PURCHASE_SETTLEMENT_LIST, config = {
            listParams = listOf("purchaseProductId" to purchaseId)
        }) { settlementFeeList ->
            purchaseProductBean?.settlementFeeList = settlementFeeList
            settlement(settlementFeeList)
        }
    }

    private fun settlement(settlementFeeList: List<SettlementFeeBean>?) {
        table_layout_settlement.removeAllViews()
        if (settlementFeeList.isNullOrEmpty()) {
            table_layout_settlement.visibility = View.GONE
            return
        }
        table_layout_settlement.visibility = View.VISIBLE
        val fieldView = inflater.inflate(R.layout.table_row_settlement, table_layout_settlement, false)
        table_layout_settlement.addView(fieldView)
        var amount = 0.0
        settlementFeeList.forEach { settlementFeeBean ->
            amount = amount.addEx(settlementFeeBean.amount).toDouble()
            val view = inflater.inflate(R.layout.table_row_settlement, table_layout_settlement, false)
            view.find<TextView>(R.id.tv_type).text = settlementFeeBean.type
            view.find<TextView>(R.id.tv_date).text = settlementFeeBean.date.goTimeFormat()
            view.find<TextView>(R.id.tv_amount).text = settlementFeeBean.amount.toString()
            view.find<TextView>(R.id.tv_account).text = settlementFeeBean.account
            view.onLongClick {
                actionDialog(
                    "编辑" to {
                        activityForResult<SettlementFeeEditActivity>(Constants.DATA to settlementFeeBean) {
                            httpSettlement()
                        }
                    },
                    "删除" to {
                        httpGet<Any>(UrlConfig.PURCHASE_SETTLEMENT_DELETE, config = {
                            "id" to settlementFeeBean.ID
                        }) {
                            httpSettlement()
                        }
                    }
                )
            }
            table_layout_settlement.addView(view)
        }

        //修改结算总金额
        if (purchaseProductBean?.settlementTotalAmount != amount) {
            modify("settlementTotalAmount" to amount) {
                purchaseProductBean?.salesTotalAmount = it?.salesTotalAmount ?: 0.0
            }
        }
        settlementTotalAmount = amount
        layout_settlement.tv_fee.contentText = "($amount)"
        refreshFee()
    }


    private fun modify(pair: Pair<String, Double>, body: (PurchaseProductBean?) -> Unit) {
        val params = mutableListOf<Pair<String, Any>>()
        params.add("id" to purchaseId)
        params.add(pair.first to pair.second)
        httpPost<PurchaseProductBean>(UrlConfig.PURCHASE_PRODUCT_MODIFY, config = {
            listParams = params
        }) {
            body(it)
        }
    }

    /**
     * 清关费用
     */
    private fun getClearanceFeeData() {
        activityForResult<ClearanceFeeEditActivity>(
            Constants.PURCHASE_PRODUCT_ID to purchaseId,
            Constants.DATA to purchaseProductBean?.clearanceFeeList
        ) {
            purchaseProductBean?.clearanceFeeList =
                (it?.getSerializableExtra(Constants.DATA) as? List<ClearanceBean>).orEmpty()
            clearanceFee(purchaseProductBean?.clearanceFeeList)
            updateBillTotalAmount()
        }
    }

    private fun clearanceFee(clearanceFeeList: List<ClearanceBean>?) {
        if (clearanceFeeList.isNullOrEmpty()) {
            recycler_view_clearance.visibility = View.GONE
            return
        }
        recycler_view_clearance.visibility = View.VISIBLE
        clearanceAdapter?.setDataList(clearanceFeeList)
        clearanceFeeList.sumEx { it.value }.let { amount ->
            clearanceFee = amount.toDouble()
            layout_clearance.tv_fee.contentText = "($amount)"
        }
        refreshFee()
    }


    private fun fillSelector(type: String) {
        bottomSingleDialog(list = listOf("文件", "图片")) { _, s ->
            if (s == "文件") {
                fileSelected {
                    rename(type, File(it.path.orEmpty()))
                }
            } else {
                imageSelected(maxNum = 1) {
                    rename(type, File(it[0].compressPath))
                }
            }
        }
    }

    private fun rename(type: String, file: File) {
        AlertFragment.Builder(this)
            .setCustomLayoutRes(R.layout.dialog_input, object : AlertFragment.OnCustomListener {
                override fun onLayout(alert: AlertFragment, view: View) {
                    val folder = purchaseProductBean?.contractNo
                    view.tv_container_no.contentText = folder + "_"
                    view.tv_name.text = file.name
                    view.btn_positive.onClick {
                        val name = if (view.tv_input_name.contentText.isNullOrEmpty()) {
                            view.tv_name.text.toString()
                            toast("请输入文件名")
                            return@onClick
                        } else {
                            folder + "_" + view.tv_input_name.text.toString()
                        }

                        addFiles(type, name + file.path.fileSuffix, file.path)
                        alert.dismiss()
                    }
                    view.btn_negative.onClick {
                        alert.dismiss()
                    }
                }
            })
            .setCancelOnTouchOut(false)
            .show()
    }


    private fun fileInfoToLocal(fileInfo: FilesBean): File {
        val path = fileInfo.path.replace("/upload", "")
        val lastIndexOf = path.lastIndexOf("/")
        val folder = FileUtils.getSDPath(path.substring(0, lastIndexOf))
        var localPath = folder + "/" + fileInfo.name
        localPath = URLDecoder.decode(localPath, "utf-8")
        return File(localPath)
    }

    private fun fileAdapter(type: String): SlimAdapter {
        return slimAdapter<FilesBean>(R.layout.list_item_document) { bean ->
            val create =
                bean.size.fileSize + " | " + bean.createTime.goTimeFormat("yyyy-MM-dd HH:mm:ss")
            glide(R.id.iv_file_icon, bean.path.fileTypeIcon)
            text(R.id.tv_file_title, bean.name)
            text(R.id.tv_file_create, create)
            gone(R.id.iv_file_more)
            longClicked {
                actionDialog(
                    "分享" to {
                        val file = fileInfoToLocal(bean)
                        if (!file.exists()) {
                            HttpCall.download(HttpCall.baseUrl + bean.path)
                                .setUseBaseUrl(false)
                                .enqueue(object : DownloadDialogHttpCallback(
                                    this@BasePurchaseProductActivity,
                                    file,
                                    "加载中..."
                                ) {
                                    override fun onSuccess(file: File) {
                                        ShareUtils.shareFile(this@BasePurchaseProductActivity, file)
                                    }

                                    override fun onFailure(msg: String) {
                                        toast(msg)
                                        if (file.exists()) {
                                            file.delete()
                                        }
                                    }
                                })
                        } else {
                            ShareUtils.shareFile(this@BasePurchaseProductActivity, file)
                        }
                    },
                    "删除" to {
                        messageDialog(msg = "是否删除${bean.name}?") { _, _ ->
                            httpGet<Any>(UrlConfig.PURCHASE_FILE_DELETE, config = {
                                listParams = listOf("id" to bean.id)
                            }) {
                                refreshFileAdapter(type)
                            }
                        }
                    })
                false
            }

            clicked {
                if (bean.suffix == ".jpg" || bean.suffix == ".png") {
                    imageDisplay(listOf(HttpCall.baseUrl + bean.path))
                } else {
                    openFile(bean)
                }
            }
        }
    }

    private fun refreshFileAdapter(type: String = "certificate") {
        httpGet<List<FilesBean>>(UrlConfig.PURCHASE_FILE_LIST, config = {
            listParams = listOf("identification" to purchaseId, "type" to type)
        }) {
            if (type == "certificate") {
                certificateAdapter?.setDataList(it.orEmpty())
            } else {
                billAdapter?.setDataList(it.orEmpty())
            }
        }
    }


    private fun addFiles(type: String, fileName: String, filePath: String) {
        val folder = if (!purchaseProductBean?.folder.isNullOrBlank()) {
            purchaseProductBean?.folder
        } else if (!purchaseProductBean?.contractNo.isNullOrBlank()) {
            purchaseProductBean?.contractNo
        } else if (!purchaseProductBean?.containerNo.isNullOrBlank()) {
            purchaseProductBean?.containerNo
        } else {
            return
        }
        HttpCall.post(UrlConfig.PURCHASE_FILE_SAVE)
            .addFiles("files[]", listOf(File(filePath)))
            .addParam("type", type)
            .addParam("identification", purchaseId)//标识
            .addParam("folder", folder)//文件夾
            .addParam("fileName", fileName)//保存的文件名称
            .enqueue(object : UploadDialogHttpCallback<List<FilesBean>>(this) {
                override fun onSuccess(data: List<FilesBean>?, resultType: ResultType) {
                    refreshFileAdapter(type)
                }
            })
    }
}